package com.base.config;

import javax.annotation.PostConstruct;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class RabbitMqConfig {

	@Autowired
	RabbitTemplate rabbitTemplate;
	
	@Bean
	public MessageConverter messageConverter(){
		return new Jackson2JsonMessageConverter();
	}
	//RabbitMqConfig对象执行完成之后,执行此方法
	@PostConstruct
	public void initRabbitTemplate() {
		/**
		 * 消息发送到交换机之后的回调
		 */
		rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
			@Override
			public void confirm(CorrelationData correlationData, boolean ack, String cause) {
				//CorrelationData [id=75ad2fb7-8f73-40c2-beb3-203097117001],ack:true,cause:null
				log.info("correlationData:{},ack:{},cause:{}",correlationData,ack,cause);
			}
		});
		
		
		rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
			/**
			 * 只要消息没有投递到指定的队列,就触发这个方法
			 */
			@Override
			public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
				log.info("message:{},replyCode:{},replyText:{},exchange:{},routingKey:{}",message,replyCode,replyText,exchange,routingKey);
			}
		});
	}
	
	
	
}
